##last modified date: 2016.3.28
##author: dwliu

import subprocess
import os
import os.path
import datetime
import time
import sys

##find files in argv
def read_files():
	files = []
	for arg in sys.argv:
		files.append(arg)
	return files

rootdir = '/opt/informix/dbs/dbspaces'


##find dbspace_list using command 'onstat -d'
def find_dbspaces():
	#read dbspace
	try:
		#read stdout from pipe
		p = subprocess.Popen('onstat -d',stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		stdout = ''
		while True:
			line = p.stdout.readline()
			if line == '':
				break
			stdout+=line
		lines = stdout.split('\n')
		# Dbspaces
		# address          number   flags      fchunk   nchunks  pgsize   flags    owner    name
		# 100cd6028        1        0x40001    1        1        4096     N  BA    informix rootdbs
		
		# dbspace_list
		dbspace_list=[]
		for l in lines:
			tmp = l.split()
			if len(tmp) == 10:
				dbspace_list.append(tmp[9])
		
		return dbspace_list
	except Exception as e:
		print e

## clean unused dbspace files according to files and dbspace_list
def remove_file(files,dbspace_list):
	
	
	#find files for removement
	to_delete_files = []
	for dir in files:
		if not os.path.exists(dir):
			print ("clean unused dbspace failed!")
			print ("not exists: "+dir)
			sys.exit(-1)
		for parent, dirnames, filenames in os.walk(dir):
			for filename in filenames:	
				flag = False
				for dbspace in dbspace_list:
					if dbspace in filename:
						flag = True
						break
				if not flag:
					to_delete_files.append(parent+os.sep+filename)	
	
	
	#remove file
	for filename in to_delete_files:
		#decide if the file is created in the same day of removement
		remove_day = datetime.datetime.fromtimestamp(time.time()).day
		create_day = datetime.datetime.fromtimestamp(os.path.getmtime(filename)).day
		if remove_day == create_day:
			print filename +' was created the same day of removement, should not be removed.'
			continue
		print 'remove : ' + filename
		os.remove(filename)

if __name__ == "__main__":
	files = read_files()
	dbspace_list = find_dbspaces()
	remove_file(files, dbspace_list)